import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Jiange
 * @create 2021-07-16-13:38
 */
public class ReadWriteLockJian {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 0; i < 6; i++) {
            final int num = i;
            new Thread(()->{
                try {
                    myCache.put(num+"",num);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },i+"").start();
        }
        for (int i = 0; i < 6; i++) {
            final int num = i;
            new Thread(()->{
                try {
                    myCache.get(num+"");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },i+"").start();
        }
    }
}

class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    public void put(String key,Object value) throws InterruptedException {
        readWriteLock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"写操作"+key);
        TimeUnit.SECONDS.sleep(1);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写完了");
        readWriteLock.writeLock().unlock();
    }

    public Object get(String key) throws InterruptedException {
        readWriteLock.readLock().lock();
        TimeUnit.MILLISECONDS.sleep(300);
        System.out.println(Thread.currentThread().getName()+"取出数据");
        readWriteLock.readLock().unlock();
        return map.get(key);

    }
}